<?php

namespace App\Admin\Extensions\Tools;

use Encore\Admin\Facades\Admin;

class TopUp
{

    private $user_id, $title;

    public function __construct($user_id)
    {
        $this->user_id = $user_id;

        $this->title = trans('admin.top_up');
    }

    public function script()
    {
        $confirm = trans('admin.confirm');

        $cancel = trans('admin.cancel');

        $amount = trans('admin.top_up_amount');

        $invalid = trans('admin.input_value_invalid');

        $route = route('admin.top_up');

        return <<<EOT

        $('.top_up').on('click',function(){
            var obj = this;
            var user_id = $(this).attr('data-id');          

            swal({
                title: "$this->title",
                input: "text",
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "$confirm",
                showCancelButton: true,
                cancelButtonText: "$cancel",
                animation: "slide-from-top",
                inputPlaceholder: "$amount"         
            }).then(function(result){
                if(result.value || result.value == ''){ 
                    var amount = parseFloat(result.value);
   
                    if(amount <= 0 || isNaN(amount)){
                        swal('$invalid', '', 'error');
                        return;
                    }
                    
                    $.ajax({
                        method: 'post',
                        url: '$route',
                        data: {
                            id:user_id,
                            amount:amount,
                            _token:LA.token,
                        },
                        success: function (data) {
                            $.pjax.reload('#pjax-container');
            
                            if (typeof data === 'object') {
                                if (data.status) {
                                    swal(data.message, '', 'success');
                                } else {
                                    swal(data.message, '', 'error');
                                }
                            }
                        }
                    });
                }
            });   
        });
        
EOT;

    }

    protected function render()
    {
        Admin::script($this->script());

        $icon = "<i class='fa fa-dollar' style='color:red'></i>";

        return "<a href='javascript:;' class='top_up' data-id='{$this->user_id}' style='margin:2px' title='{$this->title}'>" . $icon . "</a>";
    }

    public function __toString()
    {
        return $this->render();
    }

}
